package com.example.dubboredisprovider.impl;

import com.example.dubboredisprovider.dao.StudentDao;
import model.Student;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import service.StudentService;
import javax.annotation.Resource;

@DubboService(interfaceClass = StudentService.class,timeout = 5000,version="1.0")
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentDao dao;

    /**
     *
     * @param student
     * @return result
     *  1:添加数据成功
     *  2：数据已经存在
     *  3：手机号未填写
     */
    @Override
    public int addStudent(Student student) {
        int result=0;
        if(student.getPhone()!=null) {
            Student stu = dao.selectByPhone(student.getPhone());
            if(stu!=null){
                result=2;
            }else {
                result=dao.insertStudent(student);
            }
        }else {
            result=3;
        }
        return 0;
    }

    @Resource
    private RedisTemplate redisTemplate;

    /*
        缓存穿透：每次访问redis都查不到数据，每次都要到数据库查询，也查不到。
     */
    @Override
    public Student queryStudent(Integer id) {
        //从redis查询student,使用json存储对象
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
        final String USER_KEY="STUDENT:";
        Student student=null;

        if(id!=null){
            String key=USER_KEY+id;
//            从redis中查询数据
            student = (Student) redisTemplate.opsForValue().get(key);

            if(student==null){
//                从数据库中查询数据
                student= dao.selectById(id);
                if(student!=null){
                    redisTemplate.opsForValue().set(key,student);
                }else{
                    //数据库查不到，在redis添加一个id默认值
                    redisTemplate.opsForValue().set(key,Student.defaultStudent());
                }
            }
        }
        return student;
    }
}
